<template>
	<view></view>
</template>

<script>

import { getLocation } from '../../utils/getLocation';
import { getGroupMsg, getPersonMsg } from '../../utils/getMsgHistory.js';
import { getPolygon, isPointInPolygon, getGroup } from '../../utils/polygonInMap';
import { distanceNum } from '../../utils/distance.js';
const linli = uniCloud.importObject('linliChat',{customUI:true});

export default {
	data() {
		return {
			group: {}
		};
	},

	async onShow() {
		console.log('stat页show');
		this.start();
	},
	methods: {
		async start() {
			try {
				const userTel = await this.getUserTelStore();
				if (!userTel) {
					uni.navigateTo({ url: '/pages/login/login' });
					return;
				}
				const push = await uni.getPushClientId();
				const cid = push[1].cid;
				const res = await linli.getUserFromDb(userTel, cid);
				if (!res || !res.user) {
					throw new Error('用户信息为空');
				}
				if (!res.user.userId) {
					throw new Error('用户缺少userId');
				}

				this.$store.commit('msg/SET_user', res.user);
				this.$store.commit('msg/SET_stateConfig',res.user.stateConfig)

				// 若 bindDeviceToUser 是异步，必须 await
				await getApp().bindDeviceToUser(res.user.userId);

				const location = await this.$store.dispatch('msg/getLocation');

				console.log('位置信息：', location);

				// 等待 WebSocket 连接完成（假设 connectWebSocket 返回 Promise）
				const isws = await this.$store.dispatch('msg/connectWebSocket', {
					location,
					userTel
				});

				this.group = await getGroup(location);

				if (isws) {
					// 若消息拉取是异步，等待完成后再跳转
					await getGroupMsg(res.user);
					await getPersonMsg(res.user);

					uni.navigateTo({ url: '/pages/main/main' });
				} else {
					// 处理 WebSocket 未连接的情况（如重试或提示）
					console.error('WebSocket 未连接成功');
					uni.showToast({ title: '连接失败，请重试', icon: 'none' });
				}
			} catch (e) {
				console.error('初始化失败：', e);
				uni.showToast({ title: '初始化失败' + e, icon: 'none', duration: 3000 });
			}
		},
		//取内存电话
		getUserTelStore() {
			try {
				const userTel = uni.getStorageSync('userTel');

				return userTel;
			} catch (err) {
				console.error('同步获取用户手机号失败:', err);
				return null;
			}
		}

	}
};
</script>

<style></style>
